<template>
  <div class="page-wrapper">
    <div class="date-select">
      <span style="display:inline-block; margin-right: 10px;">日期选择:</span>
      <el-date-picker
        v-model="date"
        type="date"
        placeholder="选择日期"
        :picker-options="pickerOptions"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        size="mini"
        @change="dateChange"
      ></el-date-picker>
    </div>
    <div class="container">
      <c-box title="设备列表" class="byqs-wrapper box-item">
        <div class="byqs">
          <load-data-wrapper :status="byqStatus">
            <div v-if="byqs.length > 0" class="byq-list">
              <div
                v-for="(v, i) in byqs"
                :key="i"
                :class="{active: v.name === curByq}"
                class="byq"
                @click="selectByq(v)"
              >
                <div class="circle">
                  <p :title="v.name" class="name">{{ v.name }}</p>
                  <div style="position: relative;">
                    <img src="@/assets/icon/椭圆 22 副本 4@2x.png" alt />
                    <span>{{ v.dTotal || '-' }}</span>
                  </div>
                </div>
                <div class="col">
                  <div class="item">
                    <div>目标值</div>
                    <div>{{ v.dMonth || '-' }}</div>
                  </div>
                  <div class="item">
                    <div>上月完成量</div>
                    <div>{{ v.sTotal || '-' }}</div>
                  </div>
                </div>
                <div class="col">
                  <div class="item">
                    <div>完成值比</div>
                    <div>
                      <img v-if="v.dTotal < v.dMonth" src="@/assets/icon/形状 258 副本 2@2x.png" alt />
                      <img v-else src="@/assets/icon/形状 258 副本@2x.png" alt />
                      {{ ((v.dTotal/v.dMonth * 100) ? (v.dTotal/v.dMonth * 100).toFixed(2) : '-') + '%' }}
                    </div>
                  </div>
                  <div class="item">
                    <div>完成值比</div>
                    <div>
                      <img v-if="v.dTotal < v.sTotal" src="@/assets/icon/形状 258 副本 2@2x.png" alt />
                      <img v-else src="@/assets/icon/形状 258 副本@2x.png" alt />
                      {{ ((v.dTotal/v.sTotal * 100) ? (v.dTotal/v.sTotal * 100).toFixed(2) : '-') + '%' }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </load-data-wrapper>
        </div>
      </c-box>
      <c-box title="能效等级" class="box-item">
        <load-data-wrapper :status="loadStatus2">
          <echart-wrapper :option="option2"></echart-wrapper>
        </load-data-wrapper>
        <!-- <div v-if="load2" id="echarts-2" class="echarts"></div>
        <c-empty v-else></c-empty>-->
      </c-box>
      <c-box title="得分排名与容载比" class="box-item box-item-3">
        <div class="box-item-3-wrapper">
          <load-data-wrapper :status="scoreStatus" style="flex: 1">
            <div class="ranking" style="padding: 10px; box-size: border-box;">
              <div style="margin-bottom: 10px; font-size: 14px;">经济得分排名</div>
              <div class="wrapper">
                <div v-for="(v, i) in rankings" :key="i">
                  <div
                    class="name"
                  >{{ v.client + '-' + v.dstbtroom + '-' + v.transformer + '(' + v.hejiscore + ')' }}</div>
                  <div class="score" :style="{width: v.hejiscore + '%'}"></div>
                </div>
              </div>
            </div>
          </load-data-wrapper>
          <load-data-wrapper :status="loadStatus11" style="flex: 1">
            <echart-wrapper :option="option11"></echart-wrapper>
          </load-data-wrapper>
          <load-data-wrapper :status="loadStatus12" style="flex: 1">
            <echart-wrapper :option="option12"></echart-wrapper>
          </load-data-wrapper>
          <load-data-wrapper :status="loadStatus13" style="flex: 1">
            <echart-wrapper :option="option13"></echart-wrapper>
          </load-data-wrapper>
          <!-- <div id="echarts-1" class="echarts" style="flex: 1"></div> -->
        </div>
      </c-box>
      <c-box title="峰谷差月统计图(kw)" class="box-item box-item-4">
        <load-data-wrapper :status="loadStatus3">
          <echart-wrapper :option="option3"></echart-wrapper>
        </load-data-wrapper>
      </c-box>
    </div>
  </div>
</template>

<script>
import {
  getTraWholeLoad,
  getRealKzValue,
  getTraEconomicsScore,
  getTraFzAndRz
} from "@/api/power";
import { getMonthDay, getLastMonth, getLastDayOfMonth } from "@/utils";
import { colors, color, textColor, grid, legend, title } from "@/utils/echarts";
import CBox from "@/components/PageCard";
const now = getLastDayOfMonth(getLastMonth(new Date()));
import LoadDataWrapper from "@/components/base/LoadDataWrapper";
import EchartWrapper from "@/components/EchartWrapper";
export default {
  name: "Switchers",
  components: {
    CBox,
    LoadDataWrapper,
    EchartWrapper
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() >= now;
        }
      },
      date: now,
      echarts1: null,
      echarts2: null,
      echarts3: null,
      echarts4: null,
      byqs: [],
      curByq: "",
      kfValue: null,
      pdfs: [],
      rankings: null,
      curPdf: 1,
      fgcData: [],

      byqStatus: "loading",
      scoreStatus: "loading",
      loadStatus11: "loading",
      loadStatus12: "loading",
      loadStatus13: "loading",
      loadStatus2: "loading",
      loadStatus3: "loading",
      option11: null,
      option12: null,
      option13: null,
      option2: null,
      option3: null
    };
  },
  computed: {
    noLevel() {
      if (!this.kfValue) {
        return;
      }
      var level,
        noLevel1 = this.kfValue.noloadLoss1Val,
        noLevel2 = this.kfValue.noloadLoss2Val,
        // noLevel3 = this.kfValue.noloadLoss3Val,
        noData = this.kfValue.noloadLoss;
      if (noData < noLevel1) {
        level = 1;
      } else if (noData < noLevel2) {
        level = 2;
      } else {
        level = 3;
      }
      return level;
    },
    loadLevel() {
      if (!this.kfValue) return;
      var level,
        loadLevel1 = this.kfValue.loadLoss1Val,
        loadLevel2 = this.kfValue.loadLoss2Val,
        loadData = this.kfValue.loadLoss;
      if (loadData < loadLevel1) {
        level = 1;
      } else if (loadData < loadLevel2) {
        level = 2;
      } else {
        level = 3;
      }
      return level;
    },
    comId() {
      return this.$store.getters.comId;
    }
  },
  async mounted() {
    try {
      await this.getTraEconomicsScore();
      if (this.byqs.length === 0) {
        this.byqStatus = "empty";
        this.scoreStatus = "empty";
        this.loadStatus11 = "empty";
        this.loadStatus12 = "empty";
        this.loadStatus13 = "empty";
        this.loadStatus3 = "empty";
        this.loadStatus2 = "empty";
        return;
        // return this.$alert("该用户无变压器数据");
      }
      this.byqStatus = "load";
      this.curByq = this.byqs[0].name;
      await Promise.all([
        this.getRealKzValue(this.curByq),
        this.getTraFzAndRz(this.curByq),
        this.getTraWholeLoad(this.curByq)
      ]);
    } catch (e) {
      console.error(e);
      this.byqStatus = "error";
      this.loadStatus11 = "error";
      this.loadStatus12 = "error";
      this.loadStatus13 = "error";
      this.loadStatus3 = "error";
      this.loadStatus2 = "error";
    }
    try {
      await this.getTraByqPm();
      if (!this.rankings) {
        this.scoreStatus = "error";
      } else if (this.rankings.length === 0) {
        this.scoreStatus = "empty";
      } else {
        this.scoreStatus = "load";
      }
    } catch (e) {
      console.error(e);
      this.scoreStatus = "error";
    }
  },
  methods: {
    setOption1(_data, cycle) {
      var rData = [],
        fData = [],
        xData = [];
      const color = colors[0];
      _data.forEach(e => {
        xData.push(e.dstbtRoom + "-" + e.transformer);
        rData.push(e.capLoadRatio);
        fData.push(e.maxLoadRatio);
      });
      const option = {
        color: colors,
        title: {
          ...title,
          left: "center",
          text: `最大容载比与最大负载率(${cycle})`
        },
        textStyle: {
          color: textColor
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
            show: false
          }
        },
        legend: {
          ...legend,
          show: false
        },
        grid,
        xAxis: {
          type: "category",
          data: xData,
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        },
        yAxis: [
          {
            type: "value",
            show: false
          },
          {
            type: "value",
            show: false
          }
        ],
        series: [
          {
            name: "容载比",
            type: "bar",
            data: rData,
            itemStyle: {
              color: color
            },
            barWidth: "50%"
          },
          {
            name: "最大负载率",
            type: "line",
            yAxisIndex: 1,
            data: fData
          }
        ]
      };
      return option;
    },
    setOption2() {
      const color1 = colors[0],
        color2 = colors[2],
        color3 = colors[1];
      if (this.kfValue instanceof Object) {
        var noLevel1 = this.kfValue.noloadLoss1Val,
          noLevel2 = this.kfValue.noloadLoss2Val,
          noLevel3 = this.kfValue.noloadLoss3Val,
          loadLevel1 = this.kfValue.loadLoss1Val,
          loadLevel2 = this.kfValue.loadLoss2Val,
          loadLevel3 = this.kfValue.loadLoss3Val,
          noData = this.kfValue.noloadLoss,
          loadData = this.kfValue.loadLoss,
          levle = this.noLevel > this.loadLevel ? this.noLevel : this.loadLevel,
          levelColor = color1;
      }
      if (levle === 1) {
        levelColor = color1;
      } else if (levle === 2) {
        levelColor = color2;
      } else {
        levelColor = color3;
      }
      const option = {
        textStyle: {
          color: textColor
        },
        title: [
          {
            text: "能效等级：" + levle + "级",
            x: "50%",
            textAlign: "center",
            y: "1%",
            textStyle: { fontSize: 24, color: levelColor, fontWeight: "bold" }
          }
          // {
          //   text: "实际负载损耗",
          //   x: "2%",
          //   textAlign: "left",
          //   y: "2%",
          //   textStyle: { fontSize: 14, color: textColor, fontWeight: "normal" }
          // },
          // {
          //   text: "实际空载损耗",
          //   x: "97%",
          //   textAlign: "right",
          //   y: "2%",
          //   textStyle: { fontSize: 16, color: textColor, fontWeight: "normal" }
          // }
        ],
        tooltip: {
          show: true,
          formatter: " 当前损耗：{c} {b}"
        },
        series: [
          {
            type: "gauge",
            center: ["25%", "60%"], // 默认全局居中
            radius: "90%",
            splitNumber: 10, // 刻度数量
            min: 0,
            max: noLevel3,
            startAngle: 210,
            endAngle: -30,
            clockwise: true,
            title: {
              textStyle: {
                color: color
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                width: 20,
                color: [
                  [noLevel1 / noLevel3, color1],
                  [noLevel2 / noLevel3, color2],
                  [1, color3]
                ]
              }
            },
            axisTick: {
              show: false,
              lineStyle: {
                color: color,
                width: 1
              }
            },
            splitLine: {
              length: 20,
              lineStyle: {
                color: "auto"
              }
            },
            axisLabel: {
              // backgroundColor: "auto",
              borderRadius: 2,
              color: "auto",
              padding: 3,
              textShadowBlur: 2,
              textShadowOffsetX: 1,
              textShadowOffsetY: 1,
              textShadowColor: "#222",
              formatter: v => parseFloat(v).toFixed(1)
            },
            pointer: {
              // 仪表盘指针
              show: true,
              width: 4
            },
            // detail: {
            //   show: false
            // },
            detail: {
              show: true,
              textStyle: {
                fontSize: 16,
                textAlign: "center",
                lineHeight: 30
              },
              formatter: () => {
                return "负载等级: " + this.noLevel + "级";
              }
            },
            data: [
              {
                name: "kw",
                value: noData
              }
            ]
          },
          {
            type: "gauge",
            center: ["75%", "60%"], // 默认全局居中
            radius: "90%",
            splitNumber: 10, // 刻度数量
            min: 0,
            max: loadLevel3,
            startAngle: 210,
            endAngle: -30,
            clockwise: true,
            title: {
              textStyle: {
                color: color
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                width: 20,
                color: [
                  [loadLevel1 / loadLevel3, color1],
                  [loadLevel2 / loadLevel3, color2],
                  [1, color3]
                ]
              }
            },
            axisTick: {
              show: false,
              lineStyle: {
                color: color,
                width: 1
              }
            },
            splitLine: {
              length: 20,
              lineStyle: {
                color: "auto"
              }
            },
            axisLabel: {
              // backgroundColor: "auto",
              borderRadius: 2,
              color: "auto",
              padding: 3,
              textShadowBlur: 2,
              textShadowOffsetX: 1,
              textShadowOffsetY: 1,
              textShadowColor: "#222",
              formatter: v => parseFloat(v).toFixed(1)
            },
            pointer: {
              // 仪表盘指针
              show: true,
              width: 4
            },
            // detail: {
            //   show: false
            // },
            detail: {
              show: true,
              textStyle: {
                fontSize: 16,
                textAlign: "center",
                lineHeight: 30
              },
              formatter: () => {
                return "空载等级: " + this.loadLevel + "级";
              }
            },
            data: [
              {
                name: "kw",
                value: loadData
              }
            ]
          }
        ]
      };
      // this.echarts2.setOption(option);
      this.option2 = option;
    },
    setOption3() {
      const xData = [],
        data = [],
        data2 = [],
        data3 = [];
      const n = getMonthDay(this.date);
      for (let i = 1; i <= n; i++) {
        xData.push(i);
        const item = this.fgcData.find(e => parseInt(e.day) === i);
        if (item) {
          data.push(item.pkvlyDiffer);
          data2.push(item.maxPLoad);
          data3.push(item.minPLoad);
        } else {
          data.push(null);
          data2.push(null);
          data3.push(null);
        }
      }
      const option = {
        color: colors,
        textStyle: {
          color: textColor
        },
        xAxis: {
          type: "category",
          name: "日期",
          axisLine: {
            lineStyle: {
              color: textColor
            }
          },
          axisTick: { show: false },
          data: xData
        },
        legend,
        yAxis: {
          type: "value",
          splitLine: { show: false },
          axisLine: {
            lineStyle: {
              color: textColor
            }
          },
          axisTick: { show: false }
        },
        grid,
        tooltip: {
          trigger: "axis"
        },
        series: [
          {
            name: "峰谷差",
            data: data,
            smooth: true,
            type: "line"
          },
          {
            name: "最大有功负荷",
            type: "line",
            smooth: true,
            data: data2
          },
          {
            name: "最小有功负荷",
            type: "line",
            smooth: true,
            data: data3
          }
        ]
      };
      // this.echarts3.setOption(option);
      this.option3 = option;
    },
    async getTraEconomicsScore() {
      const res = await getTraEconomicsScore(this.comId);
      const data = res.data;
      if (data.dy.length > 0) {
        for (let i = 0; i < data.dy.length; i++) {
          this.byqs.push({
            name: data.dy[i].dstbtroom + "-" + data.dy[i].transformer,
            dTotal: data.dy[i].hejiscore,
            dMonth: data.dy[i].monthscore,
            sTotal: data.sy[i].hejiscore,
            sMonth: data.sy[i].monthscore
          });
        }
      } else if (data.sy.length > 0) {
        for (let i = 0; i < data.sy.length; i++) {
          this.byqs.push({
            name: data.sy[i].dstbtroom + "-" + data.sy[i].transformer,
            dTotal: data.dy[i] && data.dy[i].hejiscore,
            dMonth: data.dy[i] && data.dy[i].monthscore,
            sTotal: data.sy[i] && data.sy[i].hejiscore,
            sMonth: data.sy[i] && data.sy[i].monthscore
          });
        }
      }
    },
    async getTraFzAndRz(byq) {
      try {
        const res = await getTraFzAndRz(this.comId, this.date, byq);
        const data = res.data;
        this.rzbData = data;
        if (!data) {
          this.loadStatus11 = "error";
          this.loadStatus12 = "error";
          this.loadStatus13 = "error";
        } else {
          const { year, month, day } = data;
          if (year instanceof Array && year.length > 0) {
            this.loadStatus11 = "load";
            this.option11 = this.setOption1(year, "年");
          } else {
            this.loadStatus11 = "empty";
          }
          if (month instanceof Array && month.length > 0) {
            this.loadStatus12 = "load";
            this.option12 = this.setOption1(month, "月");
          } else {
            this.loadStatus12 = "empty";
          }
          if (day instanceof Array && day.length > 0) {
            this.loadStatus13 = "load";
            this.option13 = this.setOption1(day, "日");
          } else {
            this.loadStatus13 = "empty";
          }
        }
      } catch (error) {
        console.error(error);
        this.loadStatus11 = "error";
        this.loadStatus12 = "error";
        this.loadStatus13 = "error";
      }
    },
    async getTraWholeLoad(byq) {
      try {
        const res = await getTraWholeLoad(this.comId, this.date, byq);
        this.fgcData = res.data;
        if (!this.fgcData) {
          this.loadStatus3 = "error";
        } else if (this.fgcData.length === 0) {
          this.loadStatus3 = "empty";
        } else {
          this.loadStatus3 = "load";
          this.setOption3();
        }
      } catch (e) {
        this.loadStatus3 = "error";
      }
    },
    async getRealKzValue(byq) {
      try {
        const res = await getRealKzValue(this.comId, this.date, byq);
        const data = res.data;
        if (!data) {
          this.loadStatus2 = "error";
        } else if (data.length === 0) {
          this.loadStatus2 = "empty";
        } else {
          this.loadStatus2 = "load";
          this.kfValue = data[0];
          this.setOption2();
        }
      } catch (e) {
        console.error(e);
        this.loadStatus2 = "error";
      }
    },
    async selectByq(v) {
      if (v.name === this.curByq) return;
      this.curByq = v.name;
      await Promise.all([
        this.getTraWholeLoad(v.name),
        this.getRealKzValue(v.name)
      ]);
    },
    async dateChange() {
      await Promise.all([
        this.getTraFzAndRz(this.curByq),
        this.getTraWholeLoad(this.curByq),
        this.getRealKzValue(this.curByq)
      ]);
      this.setOption1();
    },
    async getTraByqPm() {
      const post = { clientId: this.comId };
      const res = await this.$axios.post("/eng/tra/traByqPm", post);
      this.rankings = res.data;
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
.page-wrapper {
  display: flex;
  flex-direction: column;
  height: calc(100% - 40px);
  .date-select {
    text-align: left;
    height: 40px;
  }
  .container {
    height: calc(100% - 40px);
    overflow: hidden;
    flex: 1;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(3, 1fr);
    grid-gap: 10px;
    .box-item {
      overflow: hidden;
    }
    .box-item-3,
    .box-item-4 {
      grid-column-start: 1;
      grid-column-end: 3;
    }
    .box-item-3-wrapper {
      display: flex;
      height: 100%;
    }
  }
}
.ranking {
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
  font-size: 14px;
  color: #4d576c;
  .wrapper {
    text-align: left;
    position: relative;
    .name {
      @include ellipsis;
      margin-bottom: 4px;
    }
    .score {
      display: inline-block;
      height: 10px;
      margin-bottom: 6px;
    }
    & > div {
      font-size: 14px;
      &:nth-child(1) {
        color: #008beb;
        .score {
          background: #008beb;
        }
      }
      &:nth-child(2) {
        color: #ff66bb;
        .score {
          background: #ff66bb;
        }
      }
      &:nth-child(3) {
        color: #ff9d3d;
        .score {
          background: #ff9d3d;
        }
      }
      &:nth-child(4) {
        color: #7979f8;
        .score {
          background: #7979f8;
        }
      }
    }
  }
}
.byqs {
  position: relative;
  overflow: hidden;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  height: 100%;
  overflow: auto;
  box-sizing: border-box;
  >>> .byq-list {
    padding: 10px;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 10px;
  }
  .byq {
    display: flex;
    border: 1px solid #bbb;
    align-items: stretch;
    padding: 10px;
    font-size: 14px;
    cursor: pointer;
    &.active {
      background: #f0f0f0;
    }
    .col {
      .item {
        margin-top: 10px;
        margin-left: 8px;
        height: 36px;
        width: 80px;
        &:nth-child(1) {
          margin-top: 0;
        }
        & > div {
          display: flex;
          align-items: center;
          justify-content: center;
          img {
            margin-right: 8px;
          }
        }
      }
    }
    .circle {
      position: relative;
      .name {
        width: 60px;
        @include ellipsis;
        margin: 0;
        margin-bottom: 10px;
      }
      img {
        width: 60px;
      }
      span {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }
  }
}
</style>
